# apps/audit/middleware.py
from django.utils.deprecation import MiddlewareMixin
from django.core.handlers.wsgi import WSGIRequest

class AuditLogMiddleware(MiddlewareMixin):
    @staticmethod
    def process_request(request: WSGIRequest):
        # 获取 X-Forwarded-For 并取第一个 IP（最左边），去除空格
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            client_ip = x_forwarded_for.split(',')[0].strip()  # ← 关键：取第一个 IP
        else:
            client_ip = request.META.get('REMOTE_ADDR')

        request.client_ip = client_ip
        request.user_agent = request.META.get('HTTP_USER_AGENT', '')[:500]